package com.facebank.usersupport.service.impl;

import com.facebank.usersupport.mapper.usersupport.usersupport.*;
import com.facebank.usersupport.model.*;
import com.facebank.usersupport.service.IJsonpService;
import com.facebank.usersupport.util.CollaborativeUtil;
import com.facebank.usersupport.util.SessionUtil;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpSession;
import java.util.*;

@Service
public class JsonpServiceImpl implements IJsonpService{
    @Autowired
    private AssociatorMapper associatorMapper;
    @Autowired
    private ActivityMapper activityMapper;
    @Autowired
    private DgutMessageMapper dgutMessageMapper;
    @Autowired
    private VisitsMapper visitsMapper;
    @Autowired
    private DgutEvaluateMapper dgutEvaluateMapper;

    private static final Logger logger = LoggerFactory.getLogger(JsonpServiceImpl.class);

    /**
     * 注冊
     * @param phone
     * @param password
     * @param password_confirm
     * @param email
     * @return
     */
    @Override
    public RestModel register(String phone, String password, String password_confirm, String email) {
        Boolean hasPhone = checkPhone(phone);
        if (hasPhone){return new RestModel("手机号已被注册");}
        if (!password.equals(password_confirm)){return new RestModel("205","两次密码不一致");}
        Associator associator = new Associator();
        associator.setPassword(password);
        associator.setPhone(phone);
        associator.setEmail(email);
        associatorMapper.insertSelective(associator);
        return new RestModel("注册陈功！");
    }

    /**
     * 登陸
     * @param username
     * @param password
     * @param session
     * @return
     */
    @Override
    public RestModel login(String username, String password, HttpSession session) {
       Associator associator = associatorMapper.selectAssocitorByName(username);
        SessionUtil.setAssociator(session,associator);
        SessionUtil.setAssociatorId(session,associator.getAssociatorId().toString());
       if (associator.getPassword().equals(password)){return new RestModel("登录成功");}
        return new RestModel("205","帐号或密码不正确");
    }

    /**
     * 活動展示
     * @param route_type
     * @return
     */
    @Override
    public RestModel activityShow(Short route_type) {
        List<Activity> activities =activityMapper.selectActivityByTypeId(route_type);
        return new RestModel(activities);
    }

    /**
     * 個人信息
     * @param assId
     * @return
     */
    @Override
    public RestModel personal(Long assId) {
        Associator associator = associatorMapper.selectByPrimaryKey(assId);
        associator.setPassword("");
        return new RestModel(associator);
    }

    /**
     * 修改個人信息
     * @param associator
     * @return
     */
    @Override
    public RestModel changePersonal(Associator associator) {
        int is_success = associatorMapper.updateByPrimaryKeySelective(associator);
        return new RestModel("修改成功");
    }

    /**
     * 獲取活動詳情
     * @param id
     * @return
     */
    @Override
    public RestModel detail(Integer id) {
        return new RestModel(activityMapper.selectByPrimaryKey(id));
    }

    /**
     * 修改密碼
     * @param password
     * @param confirmPassword
     * @param session
     * @return
     */
    @Override
    public RestModel changePassword(String password, String confirmPassword,HttpSession session) {
        if (!password.equals(confirmPassword)){return new RestModel("205","密码不一致");}
           Associator associator = SessionUtil.getAssociator(session);
           associator.setPassword(password);
           int is_success = associatorMapper.updateByPrimaryKeySelective(associator);
         if (is_success==1){return new RestModel("修改成功");}
        return new RestModel("205","修改失败");
    }

    /**
     * 消息顯示
     * @return
     */
    @Override
    public RestModel message() {
        return new RestModel(dgutMessageMapper.showMessage());
    }

    @Override
    public RestModel activityList() {
        return new RestModel(activityMapper.selectActivityList());
    }

    /**
     * 返回个性化推荐活动列表
     * @return
     */
    @Override
    public RestModel guessActivityList(String id) {
        List<Visits> visitsList = visitsMapper.selectVisitsList();
        List<Activity> activityList = new ArrayList<Activity>();
        if(10 == visitsList.size()){
            Random random = new Random();
            int i = random.nextInt(9);
            activityList.add(activityMapper.selectByPrimaryKey(visitsList.get(i).getActivityId()));
            activityList.add(activityMapper.selectByPrimaryKey(visitsList.get(i+1).getActivityId()));
        }
        //返回随机活动列表给游客
        List<Activity> randActivityList = new ArrayList<Activity>();
        randActivityList = activityMapper.selectRandActivityList();
        if(StringUtils.isBlank(id)){
            for(int i=0;i<8;i++){
                activityList.add(randActivityList.get(i));
            }
            return new RestModel(activityList);
        }
        List<DgutEvaluate> dgutEvaluateList = new ArrayList<DgutEvaluate>();
        dgutEvaluateList = dgutEvaluateMapper.selectAssociatorEvaluateList(Long.valueOf(id));
        if(dgutEvaluateList.size()>=2){
            List<DgutEvaluate> dgutEvaluates = new ArrayList<DgutEvaluate>();
            dgutEvaluates = dgutEvaluateMapper.selectEvaluateAssociator();
            logger.info(dgutEvaluates.toString());
            if(dgutEvaluates.size()<5){
                for(int i=0;i<8;i++){
                    activityList.add(randActivityList.get(i));
                }
                return new RestModel(activityList);
            }
            long[] associatorIds = new long[5];
            for(int i=0;i<5;i++){
                int j = new Random().nextInt(dgutEvaluates.size());
                associatorIds[i] = dgutEvaluates.get(j).getAssociatorId();
                dgutEvaluates.remove(j);
            }
            Map score = new HashMap();
            score = data(dgutEvaluateList,associatorIds);
            Map scores = CollaborativeUtil.outNearbyUserList(Long.valueOf(id),associatorIds,score);
            List<Map.Entry<Long, Double>> wordMap = new ArrayList<Map.Entry<Long, Double>>(scores.entrySet());
            Collections.sort(wordMap, new Comparator<Map.Entry<Long, Double>>() {//根据value排序
                public int compare(Map.Entry<Long, Double> o1,
                                   Map.Entry<Long, Double> o2) {
                    double result = o1.getValue() - o2.getValue();
                    if(result > 0)
                        return 1;
                    else if(result == 0)
                        return 0;
                    else
                        return -1;
                }
            });
            int flag = 0;
            for(Map.Entry<Long, Double> set:wordMap){
                List<DgutEvaluate> dgutEvaluateList1 = dgutEvaluateMapper.selectAssociatorEvaluateList(set.getKey());
                dgutEvaluateList1.removeAll(dgutEvaluateList);
                for (DgutEvaluate dgutEvaluate:dgutEvaluateList){
                    for (int i = 0; i<dgutEvaluateList1.size();i++) {
                        if (dgutEvaluateList1.get(i).getActivityId()==dgutEvaluate.getActivityId()){
                            dgutEvaluateList1.remove(i);
                        }
                    }
                }
                for (DgutEvaluate dgutEvaluate1:dgutEvaluateList1){
                    flag++;
                    logger.info(dgutEvaluate1.getActivityId().toString());
                    //logger.info("========"+activityMapper.selectByPrimaryKey(Integer.parseInt(dgutEvaluate1.getActivityId().toString())).toString());
                    activityList.add(activityMapper.selectByPrimaryKey(dgutEvaluate1.getActivityId().intValue()));
                    if (flag>=7){
                        break;
                    }
                }
                if (flag>=7){
                    break;
                }
            }
            for(int i=0;i<10-activityList.size();i++){
                logger.info("999999999999999999999999999999999999");
                activityList.add(randActivityList.get(i));
            }
            return new RestModel(activityList);
        }else{
            for(int i=0;i<8;i++){
                activityList.add(randActivityList.get(i));
            }
            return new RestModel(activityList);
        }
    }

    //处理数据集
    private Map data(List<DgutEvaluate> dgutEvaluateList,long[] associatorIds){
        Map score = new HashMap();
        for (int i=0;i<5;i++){
            HashMap tempScore = new HashMap();
            for(DgutEvaluate dgutEvaluate:dgutEvaluateList){
                DgutEvaluate dgutEvaluate1 = dgutEvaluateMapper.selectByActivityId(associatorIds[i],dgutEvaluate.getActivityId());
                if (null != dgutEvaluate1){
                    tempScore.put(dgutEvaluate1.getActivityId(),dgutEvaluate1.getLevel());
                }else {
                    tempScore.put(dgutEvaluate.getActivityId(),0);
                }
            }
            score.put(associatorIds[i],tempScore);
        }
        HashMap tempScore = new HashMap();
        for(DgutEvaluate dgutEvaluate:dgutEvaluateList){
            tempScore.put(dgutEvaluate.getActivityId(),dgutEvaluate.getLevel());
        }
        score.put(dgutEvaluateList.get(0).getAssociatorId(),tempScore);
        return score;
    }

    /**
     * 显示活动评价
     * @param actId
     * @return
     */
    @Override
    public RestModel showEvaluation(Long actId) {
        return new RestModel(dgutEvaluateMapper.showEvaluateDetail(actId));
    }

    /**
     * 校驗手機號是否被注冊
     * @param phone
     * @return
     */
    //判断手机号是否存在
    public boolean checkPhone(String phone){
        Integer count =  associatorMapper.checkPhone(phone);
        if (count==0){return false;}else {return true;}
    }
}
